// 全局变量
let charts = {};
let currentData = {};

// 初始化仪表板
async function initializeDashboard() {
    showLoading();
    
    try {
        // 并行加载所有数据
        const [statsData, salesTrendData, categoryData, regionData, topProductsData] = await Promise.all([
            fetchData('/api/dashboard/stats'),
            fetchData('/api/sales/trend'),
            fetchData('/api/sales/category'),
            fetchData('/api/sales/region'),
            fetchData('/api/products/top')
        ]);

        // 更新统计数据
        updateStats(statsData.data);
        
        // 初始化图表
        initSalesTrendChart(salesTrendData.data);
        initCategoryChart(categoryData.data);
        initRegionChart(regionData.data);
        initTopProductsChart(topProductsData.data);
        
        // 更新最后更新时间
        updateLastUpdate();
        
        // 设置自动刷新
        setAutoRefresh();
        
        hideLoading();
        
    } catch (error) {
        console.error('初始化失败:', error);
        hideLoading();
        showError('数据加载失败，请检查网络连接');
    }
}

// 通用数据获取函数
async function fetchData(url) {
    try {
        const response = await fetch(url);
        const data = await response.json();
        
        if (!data.success) {
            throw new Error(data.message || '请求失败');
        }
        
        return data;
    } catch (error) {
        console.error(`获取数据失败 ${url}:`, error);
        throw error;
    }
}

// 更新统计数据
function updateStats(data) {
    document.getElementById('total-sales').textContent = `¥${formatNumber(data.total_sales)}`;
    document.getElementById('total-orders').textContent = formatNumber(data.total_orders);
    document.getElementById('total-products').textContent = formatNumber(data.total_products);
    document.getElementById('today-sales').textContent = `¥${formatNumber(data.today_sales)}`;
}

// 初始化销售趋势图
function initSalesTrendChart(data) {
    const chartDom = document.getElementById('sales-trend-chart');
    const chart = echarts.init(chartDom);
    
    const dates = data.map(item => item.date);
    const amounts = data.map(item => item.total_amount);
    const orders = data.map(item => item.order_count);
    
    const option = {
        backgroundColor: 'transparent',
        tooltip: {
            trigger: 'axis',
            backgroundColor: 'rgba(0,0,0,0.8)',
            borderColor: '#00d4ff',
            textStyle: {
                color: '#ffffff'
            }
        },
        legend: {
            data: ['销售额', '订单数'],
            textStyle: {
                color: '#ffffff'
            },
            top: 10
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: dates,
            axisLine: {
                lineStyle: {
                    color: '#8892b0'
                }
            },
            axisLabel: {
                color: '#8892b0'
            }
        },
        yAxis: [
            {
                type: 'value',
                name: '销售额 (¥)',
                axisLine: {
                    lineStyle: {
                        color: '#8892b0'
                    }
                },
                axisLabel: {
                    color: '#8892b0',
                    formatter: function(value) {
                        return formatNumber(value);
                    }
                },
                splitLine: {
                    lineStyle: {
                        color: 'rgba(255,255,255,0.1)'
                    }
                }
            },
            {
                type: 'value',
                name: '订单数',
                axisLine: {
                    lineStyle: {
                        color: '#8892b0'
                    }
                },
                axisLabel: {
                    color: '#8892b0'
                },
                splitLine: {
                    show: false
                }
            }
        ],
        series: [
            {
                name: '销售额',
                type: 'line',
                smooth: true,
                data: amounts,
                itemStyle: {
                    color: '#00d4ff'
                },
                lineStyle: {
                    width: 3,
                    shadowColor: 'rgba(0,123,255,0.5)',
                    shadowBlur: 10
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(0,123,255,0.3)' },
                        { offset: 1, color: 'rgba(0,123,255,0.1)' }
                    ])
                }
            },
            {
                name: '订单数',
                type: 'bar',
                yAxisIndex: 1,
                data: orders,
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#0099cc' },
                        { offset: 1, color: '#0066ff' }
                    ])
                }
            }
        ]
    };
    
    chart.setOption(option);
    charts.salesTrend = chart;
    
    // 响应式处理
    window.addEventListener('resize', () => chart.resize());
}

// 初始化商品类别分析图
function initCategoryChart(data) {
    const chartDom = document.getElementById('category-chart');
    const chart = echarts.init(chartDom);
    
    const categories = data.map(item => item.category);
    const amounts = data.map(item => item.total_amount);
    
    const option = {
        backgroundColor: 'transparent',
        tooltip: {
            trigger: 'item',
            backgroundColor: 'rgba(0,0,0,0.8)',
            borderColor: '#00d4ff',
            textStyle: {
                color: '#ffffff'
            },
            formatter: function(params) {
                return `${params.name}<br/>销售额: ¥${formatNumber(params.value)}<br/>占比: ${params.percent}%`;
            }
        },
        legend: {
            orient: 'vertical',
            left: 'left',
            textStyle: {
                color: '#ffffff'
            }
        },
        series: [
            {
                name: '商品类别',
                type: 'pie',
                radius: ['40%', '70%'],
                center: ['60%', '50%'],
                data: categories.map((category, index) => ({
                    name: category,
                    value: amounts[index]
                })),
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: false
                },
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ],
        color: ['#00d4ff', '#0099cc', '#0066ff', '#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57']
    };
    
    chart.setOption(option);
    charts.category = chart;
    
    window.addEventListener('resize', () => chart.resize());
}

// 初始化地区销售分布图
function initRegionChart(data) {
    const chartDom = document.getElementById('region-chart');
    const chart = echarts.init(chartDom);
    
    const regions = data.map(item => item.region);
    const amounts = data.map(item => item.total_amount);
    
    const option = {
        backgroundColor: 'transparent',
        tooltip: {
            trigger: 'axis',
            backgroundColor: 'rgba(0,0,0,0.8)',
            borderColor: '#00d4ff',
            textStyle: {
                color: '#ffffff'
            },
            formatter: function(params) {
                return `${params[0].name}<br/>销售额: ¥${formatNumber(params[0].value)}`;
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: regions,
            axisLine: {
                lineStyle: {
                    color: '#8892b0'
                }
            },
            axisLabel: {
                color: '#8892b0',
                rotate: 45
            }
        },
        yAxis: {
            type: 'value',
            axisLine: {
                lineStyle: {
                    color: '#8892b0'
                }
            },
            axisLabel: {
                color: '#8892b0',
                formatter: function(value) {
                    return formatNumber(value);
                }
            },
            splitLine: {
                lineStyle: {
                    color: 'rgba(255,255,255,0.1)'
                }
            }
        },
        series: [
            {
                name: '销售额',
                type: 'bar',
                data: amounts,
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#00d4ff' },
                        { offset: 1, color: '#0099cc' }
                    ]),
                    borderRadius: [4, 4, 0, 0]
                },
                emphasis: {
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: '#0099cc' },
                            { offset: 1, color: '#0066ff' }
                        ])
                    }
                }
            }
        ]
    };
    
    chart.setOption(option);
    charts.region = chart;
    
    window.addEventListener('resize', () => chart.resize());
}

// 初始化热销商品排行图
function initTopProductsChart(data) {
    const chartDom = document.getElementById('top-products-chart');
    const chart = echarts.init(chartDom);
    
    const products = data.map(item => item.name);
    const quantities = data.map(item => item.total_quantity);
    
    const option = {
        backgroundColor: 'transparent',
        tooltip: {
            trigger: 'axis',
            backgroundColor: 'rgba(0,0,0,0.8)',
            borderColor: '#00d4ff',
            textStyle: {
                color: '#ffffff'
            },
            formatter: function(params) {
                return `${params[0].name}<br/>销量: ${formatNumber(params[0].value)}`;
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'value',
            axisLine: {
                lineStyle: {
                    color: '#8892b0'
                }
            },
            axisLabel: {
                color: '#8892b0'
            },
            splitLine: {
                lineStyle: {
                    color: 'rgba(255,255,255,0.1)'
                }
            }
        },
        yAxis: {
            type: 'category',
            data: products,
            axisLine: {
                lineStyle: {
                    color: '#8892b0'
                }
            },
            axisLabel: {
                color: '#8892b0',
                width: 100,
                overflow: 'truncate'
            }
        },
        series: [
            {
                name: '销量',
                type: 'bar',
                data: quantities,
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                        { offset: 0, color: '#00d4ff' },
                        { offset: 1, color: '#0099cc' }
                    ]),
                    borderRadius: [0, 4, 4, 0]
                },
                emphasis: {
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                            { offset: 0, color: '#0099cc' },
                            { offset: 1, color: '#0066ff' }
                        ])
                    }
                }
            }
        ]
    };
    
    chart.setOption(option);
    charts.topProducts = chart;
    
    window.addEventListener('resize', () => chart.resize());
}

// 刷新销售趋势图
async function refreshSalesTrend() {
    try {
        const data = await fetchData('/api/sales/trend');
        initSalesTrendChart(data.data);
        showSuccess('销售趋势数据已更新');
    } catch (error) {
        showError('刷新销售趋势数据失败');
    }
}

// 刷新商品类别图
async function refreshCategoryChart() {
    try {
        const data = await fetchData('/api/sales/category');
        initCategoryChart(data.data);
        showSuccess('商品类别数据已更新');
    } catch (error) {
        showError('刷新商品类别数据失败');
    }
}

// 刷新地区销售图
async function refreshRegionChart() {
    try {
        const data = await fetchData('/api/sales/region');
        initRegionChart(data.data);
        showSuccess('地区销售数据已更新');
    } catch (error) {
        showError('刷新地区销售数据失败');
    }
}

// 刷新热销商品图
async function refreshTopProducts() {
    try {
        const data = await fetchData('/api/products/top');
        initTopProductsChart(data.data);
        showSuccess('热销商品数据已更新');
    } catch (error) {
        showError('刷新热销商品数据失败');
    }
}

// 更新日期时间
function updateDateTime() {
    const now = new Date();
    const timeElement = document.getElementById('current-time');
    const dateElement = document.getElementById('current-date');
    
    timeElement.textContent = now.toLocaleTimeString('zh-CN');
    dateElement.textContent = now.toLocaleDateString('zh-CN');
}

// 更新最后更新时间
function updateLastUpdate() {
    const now = new Date();
    document.getElementById('last-update').textContent = now.toLocaleString('zh-CN');
}

// 设置自动刷新
function setAutoRefresh() {
    // 每5分钟自动刷新一次数据
    setInterval(async () => {
        try {
            const [statsData, salesTrendData, categoryData, regionData, topProductsData] = await Promise.all([
                fetchData('/api/dashboard/stats'),
                fetchData('/api/sales/trend'),
                fetchData('/api/sales/category'),
                fetchData('/api/sales/region'),
                fetchData('/api/products/top')
            ]);
            
            updateStats(statsData.data);
            initSalesTrendChart(salesTrendData.data);
            initCategoryChart(categoryData.data);
            initRegionChart(regionData.data);
            initTopProductsChart(topProductsData.data);
            updateLastUpdate();
            
            console.log('数据自动刷新完成');
        } catch (error) {
            console.error('自动刷新失败:', error);
        }
    }, 5 * 60 * 1000); // 5分钟
}

// 显示加载动画
function showLoading() {
    document.getElementById('loading').classList.remove('hidden');
}

// 隐藏加载动画
function hideLoading() {
    document.getElementById('loading').classList.add('hidden');
}

// 显示成功消息
function showSuccess(message) {
    showNotification(message, 'success');
}

// 显示错误消息
function showError(message) {
    showNotification(message, 'error');
}

// 显示通知
function showNotification(message, type) {
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.textContent = message;
    
    // 添加样式
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 15px 20px;
        border-radius: 8px;
        color: white;
        font-weight: 500;
        z-index: 10000;
        transform: translateX(100%);
        transition: transform 0.3s ease;
        ${type === 'success' ? 'background: linear-gradient(45deg, #4CAF50, #45a049);' : 'background: linear-gradient(45deg, #f44336, #d32f2f);'}
    `;
    
    document.body.appendChild(notification);
    
    // 显示动画
    setTimeout(() => {
        notification.style.transform = 'translateX(0)';
    }, 100);
    
    // 自动隐藏
    setTimeout(() => {
        notification.style.transform = 'translateX(100%)';
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}

// 格式化数字
function formatNumber(num) {
    if (num >= 1000000) {
        return (num / 1000000).toFixed(1) + 'M';
    } else if (num >= 1000) {
        return (num / 1000).toFixed(1) + 'K';
    } else {
        return num.toLocaleString();
    }
} 